package com.net.wanjian.networkhospitalmanager.activity.evaluate;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.adapter.EvaluateDetailsTeacherContentAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.EvaluateDetailsTeacherStarAdapter;
import com.net.wanjian.networkhospitalmanager.bean.SearchEvaluateResult;
import com.net.wanjian.networkhospitalmanager.bean.evaluate.SearchTeacherEvaluationAllInfoListResult;
import com.net.wanjian.networkhospitalmanager.consts.AppConsts;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.consts.EvaluateConst;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.widge.RefreshRecyclerView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

public class EvaluateEventDetailsActivity extends BaseActivity implements View.OnClickListener {
    public static final String EVALUATE_EVENT_DETAILS_ACTIVITY_EVENT_KEY = "evaluate_event_details_activity_event_key";
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.top_title_tv)
    TextView topTitleTv;
    @BindView(R.id.evaluate_details_teacher_content_recycler)
    RefreshRecyclerView evaluateDetailsTeacherContentRecycler;
    @BindView(R.id.evaluate_details_teacher_content_root_layout)
    LinearLayout evaluateDetailsTeacherContentRootLayout;

    TextView evaluateDetailsTeacherMultipleScoreTv;
    RecyclerView evaluateDetailsTeacherStarRecycler;

    LinearLayout evaluateDetailsTeacherEvaluateAllLayout;
    LinearLayout evaluateDetailsTeacherEvaluateGoodLayout;
    LinearLayout evaluateDetailsTeacherEvaluateMiddleLayout;
    LinearLayout evaluateDetailsTeacherEvaluateBadLayout;
    TextView evaluateAllTextTv;
    TextView evaluateAllNumTv;
    TextView evaluateGoodTextTv;
    TextView evaluateGoodNumTv;
    TextView evaluateMiddleTextTv;
    TextView evaluateMiddleNumTv;
    TextView evaluateBadTextTv;
    TextView evaluateBadNumTv;

    private EvaluateDetailsTeacherStarAdapter mEvaluateDetailsTeacherStarAdapter;
    private EvaluateDetailsTeacherContentAdapter mEvaluateDetailsTeacherContentAdapter;

    private SearchEvaluateResult.DataBean.EventListBean eventBean;
    private int currentNum = AppConsts.currentPageNum, currentPageNum, countNum;

    private List<TextView> mTextViewList = new ArrayList<>();

    private List<SearchTeacherEvaluationAllInfoListResult.DataBean.EvaluationTableListBean> evaluationTableList;
    private String mUserIdentityID;
    private int evaluateType;

    @Override
    protected void initData() {

        initHeadView();

        mTextViewList.add(evaluateAllTextTv);
        mTextViewList.add(evaluateAllNumTv);
        mTextViewList.add(evaluateGoodTextTv);
        mTextViewList.add(evaluateGoodNumTv);
        mTextViewList.add(evaluateMiddleTextTv);
        mTextViewList.add(evaluateMiddleNumTv);
        mTextViewList.add(evaluateBadTextTv);
        mTextViewList.add(evaluateBadNumTv);

        topTitleTv.setText("事件详情");
        topBackLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EvaluateEventDetailsActivity.this.finish();
            }
        });
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            eventBean = (SearchEvaluateResult.DataBean.EventListBean) bundle.getSerializable(EVALUATE_EVENT_DETAILS_ACTIVITY_EVENT_KEY);
        } else {
            return;
        }

        evaluateDetailsTeacherEvaluateAllLayout.setOnClickListener(this);
        evaluateDetailsTeacherEvaluateGoodLayout.setOnClickListener(this);
        evaluateDetailsTeacherEvaluateMiddleLayout.setOnClickListener(this);
        evaluateDetailsTeacherEvaluateBadLayout.setOnClickListener(this);

        //获取网络数据，评价详情

        //获取事件评价信息和评价列表
        getEverTeacherEvaluationAllInfoHttpRequest("");
    }

    //加载头部布局
    private void initHeadView() {
        View headerView = LayoutInflater.from(this).inflate(R.layout.head_evaluate_event_details_layout, evaluateDetailsTeacherContentRootLayout, false);
        evaluateDetailsTeacherMultipleScoreTv = (TextView) headerView.findViewById(R.id.evaluate_details_teacher_multiple_score_tv);
        evaluateDetailsTeacherStarRecycler = (RecyclerView) headerView.findViewById(R.id.evaluate_details_teacher_star_recycler);
        evaluateDetailsTeacherEvaluateAllLayout = (LinearLayout) headerView.findViewById(R.id.evaluate_details_teacher_evaluate_all_layout);
        evaluateDetailsTeacherEvaluateGoodLayout = (LinearLayout) headerView.findViewById(R.id.evaluate_details_teacher_evaluate_good_layout);
        evaluateDetailsTeacherEvaluateMiddleLayout = (LinearLayout) headerView.findViewById(R.id.evaluate_details_teacher_evaluate_middle_layout);
        evaluateDetailsTeacherEvaluateBadLayout = (LinearLayout) headerView.findViewById(R.id.evaluate_details_teacher_evaluate_bad_layout);
        evaluateAllTextTv = (TextView) headerView.findViewById(R.id.evaluate_all_text_tv);
        evaluateAllNumTv = (TextView) headerView.findViewById(R.id.evaluate_all_num_tv);
        evaluateGoodTextTv = (TextView) headerView.findViewById(R.id.evaluate_good_text_tv);
        evaluateGoodNumTv = (TextView) headerView.findViewById(R.id.evaluate_good_num_tv);
        evaluateMiddleTextTv = (TextView) headerView.findViewById(R.id.evaluate_middle_text_tv);
        evaluateMiddleNumTv = (TextView) headerView.findViewById(R.id.evaluate_middle_num_tv);
        evaluateBadTextTv = (TextView) headerView.findViewById(R.id.evaluate_bad_text_tv);
        evaluateBadNumTv = (TextView) headerView.findViewById(R.id.evaluate_bad_num_tv);
        evaluateDetailsTeacherContentRecycler.addHeaderView(headerView);
    }
    private void initTeacherStarRecycler(List<SearchTeacherEvaluationAllInfoListResult.DataBean.ComprehensiveEvaluationItemListBean> c) {
        Log.e(TAG, "initTeacherStarRecycler: "+c.size());
        //计算并设置综合得分值
        float total = 0;
        for (SearchTeacherEvaluationAllInfoListResult.DataBean.ComprehensiveEvaluationItemListBean b : c) {
            total += Float.parseFloat(b.getEventEvaluationItemValue());
        }
        float multipleScore = total / c.size();
        DecimalFormat decimalFormat = new DecimalFormat("#.0");

        String format = "0";
        if (multipleScore != 0){
            format = decimalFormat.format(multipleScore);
        }

        evaluateDetailsTeacherMultipleScoreTv.setText("综合得分：" + format);
        evaluateDetailsTeacherStarRecycler.setLayoutManager(new LinearLayoutManager(this));
        mEvaluateDetailsTeacherStarAdapter = new EvaluateDetailsTeacherStarAdapter(this);
        mEvaluateDetailsTeacherStarAdapter.setList(c);
        evaluateDetailsTeacherStarRecycler.setAdapter(mEvaluateDetailsTeacherStarAdapter);
    }

    //请求每个老师的评价信息
    private void getEverTeacherEvaluationAllInfoHttpRequest(String userIdentityID) {
        Log.e(TAG, "getEverTeacherEvaluationAllInfoHttpRequest: "+userIdentityID );
        mUserIdentityID = userIdentityID;
        setBackgroundcolorById(R.id.evaluate_all_text_tv, R.id.evaluate_all_num_tv);
        evaluateType = EvaluateConst.result_type_all_evaluate;
        ProgressDialogUtils.showProgressDialog(this, "", R.string.loading_text);
        currentPageNum = 0;
        final SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchEvaluationTableList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(), eventBean.getEventType(),
                eventBean.getEventID(), userIdentityID, EvaluateConst.event_evaluate,
                EvaluateConst.result_type_all_evaluate, currentPageNum, currentNum, new DisposableObserver<SearchTeacherEvaluationAllInfoListResult>() {
                    @Override
                    public void onNext(SearchTeacherEvaluationAllInfoListResult searchTeacherEvaluationAllInfoListResult) {
                        if (searchTeacherEvaluationAllInfoListResult.getResult() == ErrorCodeReturn.success) {
                            xmlUtil.setToken(URLDecoderUtil.getDecoder(searchTeacherEvaluationAllInfoListResult.getData().getToken()));
                            countNum = Integer.parseInt(searchTeacherEvaluationAllInfoListResult.getData().getTotalCount());

                            //加载评级 星星 列表
                            initTeacherStarRecycler(searchTeacherEvaluationAllInfoListResult.getData().getComprehensiveEvaluationItemList());

                            //加载不同类型的评价和数量
                            int all = 0, good = 0, middle = 0, bad = 0;
                            List<SearchTeacherEvaluationAllInfoListResult.DataBean.EvaluationCategoryCountBean> categoryCount = searchTeacherEvaluationAllInfoListResult.getData().getEvaluationCategoryCount();
                            for (SearchTeacherEvaluationAllInfoListResult.DataBean.EvaluationCategoryCountBean c : categoryCount) {
                                switch (Integer.parseInt(c.getResultType())) {
                                    case EvaluateConst.result_type_all_evaluate:
                                        all = Integer.parseInt(c.getEvaluationPersonNum());
                                        break;
                                    case EvaluateConst.result_type_good_evaluate:
                                        good = Integer.parseInt(c.getEvaluationPersonNum());
                                        break;
                                    case EvaluateConst.result_type_middle_evaluate:
                                        middle = Integer.parseInt(c.getEvaluationPersonNum());
                                        break;
                                    case EvaluateConst.result_type_bad_evaluate:
                                        bad = Integer.parseInt(c.getEvaluationPersonNum());
                                        break;
                                }
                            }


                            double goodPercent = 0, middlePercent = 0, badPercent = 0;
                            if (all != 0) {
                                goodPercent = (double) good / (double)all;
                                middlePercent = (double) middle / (double) all;
                                badPercent = (double) bad / (double) all;
                            }

                            DecimalFormat decimalFormat = new DecimalFormat("0.00");
                            goodPercent = Double.parseDouble(decimalFormat.format(goodPercent));
                            middlePercent = Double.parseDouble(decimalFormat.format(middlePercent));
                            badPercent = Double.parseDouble(decimalFormat.format(badPercent));

                            DecimalFormat finalDecimal = new DecimalFormat("0");

                            evaluateAllNumTv.setText(all + "");
                            evaluateGoodNumTv.setText(good + "(" +  finalDecimal.format(goodPercent * 100) + "%" + ")");
                            evaluateMiddleNumTv.setText(middle + "(" +  finalDecimal.format(middlePercent*100) + "%" + ")");
                            evaluateBadNumTv.setText(bad + "(" + finalDecimal.format(badPercent*100) + "%" + ")");

                            //加载评价列表信息
                            evaluationTableList = searchTeacherEvaluationAllInfoListResult.getData().getEvaluationTableList();

                            if (evaluationTableList.size() >0){
                               initEvaluateList(2);
                            }else {
                                initEvaluateList(0);
                            }
                            mEvaluateDetailsTeacherContentAdapter.setList(evaluationTableList);

                            //停止加载更多
                            if (searchTeacherEvaluationAllInfoListResult.getData().getEvaluationTableList().size() < currentNum || evaluationTableList.size() >= countNum) {
                                evaluateDetailsTeacherContentRecycler.refreshComplete();
                                evaluateDetailsTeacherContentRecycler.setNoMore(true);
                            } else {
                                evaluateDetailsTeacherContentRecycler.refreshComplete();
                                evaluateDetailsTeacherContentRecycler.setNoMore(false);
                            }
                        } else {
                            //停止加载更多
                            evaluateDetailsTeacherContentRecycler.refreshComplete();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });
    }

    //加载评价列表信息
    private void initEvaluateList(int mode) {
        //加载评论内容列表
        evaluateDetailsTeacherContentRecycler.setRefreshMode(mode);
        evaluateDetailsTeacherContentRecycler.setLayoutManager(new LinearLayoutManager(this));

        evaluateDetailsTeacherContentRecycler.addOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        mEvaluateDetailsTeacherContentAdapter = new EvaluateDetailsTeacherContentAdapter(this);

        evaluateDetailsTeacherContentRecycler.setAdapter(mEvaluateDetailsTeacherContentAdapter);
//        mEvaluateDetailsTeacherContentAdapter = new EvaluateDetailsTeacherContentAdapter(this);
//        mEvaluateDetailsTeacherContentAdapter.setList(evaluationTableList);
//        evaluateDetailsTeacherContentRecycler.setAdapter(mEvaluateDetailsTeacherContentAdapter);
    }

    private void loadMore() {
        currentPageNum++;
        final SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchEvaluationTableList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(), eventBean.getEventType(),
                eventBean.getEventID(), mUserIdentityID, EvaluateConst.teacher_evaluate,
                evaluateType, currentPageNum, currentNum, new DisposableObserver<SearchTeacherEvaluationAllInfoListResult>() {
                    @Override
                    public void onNext(SearchTeacherEvaluationAllInfoListResult searchTeacherEvaluationAllInfoListResult) {
                        if (searchTeacherEvaluationAllInfoListResult.getResult() == ErrorCodeReturn.success) {
                            xmlUtil.setToken(URLDecoderUtil.getDecoder(searchTeacherEvaluationAllInfoListResult.getData().getToken()));

                            List<SearchTeacherEvaluationAllInfoListResult.DataBean.EvaluationTableListBean> tableList = searchTeacherEvaluationAllInfoListResult.getData().getEvaluationTableList();
                            EvaluateEventDetailsActivity.this.evaluationTableList.addAll(tableList);
                            mEvaluateDetailsTeacherContentAdapter.setList(EvaluateEventDetailsActivity.this.evaluationTableList);

                            if (tableList.size() < currentNum || evaluationTableList.size() >= countNum) {
                                evaluateDetailsTeacherContentRecycler.setNoMore(true);
                            } else {
                                evaluateDetailsTeacherContentRecycler.loadMoreComplete();
                            }

                        } else {
                            evaluateDetailsTeacherContentRecycler.loadMoreComplete();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        evaluateDetailsTeacherContentRecycler.loadMoreComplete();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_evaluate_event_details;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    //评价好中差切换
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.evaluate_details_teacher_evaluate_all_layout:
                setBackgroundcolorById(R.id.evaluate_all_text_tv, R.id.evaluate_all_num_tv);
                evaluateType = EvaluateConst.result_type_all_evaluate;
                getEvaluateTableListByCondition();
                break;
            case R.id.evaluate_details_teacher_evaluate_good_layout:
                setBackgroundcolorById(R.id.evaluate_good_text_tv, R.id.evaluate_good_num_tv);
                evaluateType = EvaluateConst.result_type_good_evaluate;
                getEvaluateTableListByCondition();
                break;
            case R.id.evaluate_details_teacher_evaluate_middle_layout:
                setBackgroundcolorById(R.id.evaluate_middle_text_tv, R.id.evaluate_middle_num_tv);
                evaluateType = EvaluateConst.result_type_middle_evaluate;
                getEvaluateTableListByCondition();
                break;
            case R.id.evaluate_details_teacher_evaluate_bad_layout:
                setBackgroundcolorById(R.id.evaluate_bad_text_tv, R.id.evaluate_bad_num_tv);
                evaluateType = EvaluateConst.result_type_bad_evaluate;
                getEvaluateTableListByCondition();
                break;
        }
    }

    private void getEvaluateTableListByCondition() {
        ProgressDialogUtils.showProgressDialog(this, "", R.string.loading_text);
        currentPageNum = 0;
        final SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchEvaluationTableList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(), eventBean.getEventType(),
                eventBean.getEventID(), mUserIdentityID, EvaluateConst.event_evaluate,
                evaluateType, currentPageNum, currentNum, new DisposableObserver<SearchTeacherEvaluationAllInfoListResult>() {
                    @Override
                    public void onNext(SearchTeacherEvaluationAllInfoListResult searchTeacherEvaluationAllInfoListResult) {
                        if (searchTeacherEvaluationAllInfoListResult.getResult() == ErrorCodeReturn.success) {
                            xmlUtil.setToken(URLDecoderUtil.getDecoder(searchTeacherEvaluationAllInfoListResult.getData().getToken()));

                            List<SearchTeacherEvaluationAllInfoListResult.DataBean.EvaluationTableListBean> tableList = searchTeacherEvaluationAllInfoListResult.getData().getEvaluationTableList();
                            EvaluateEventDetailsActivity.this.evaluationTableList = tableList;
                            mEvaluateDetailsTeacherContentAdapter.setList(EvaluateEventDetailsActivity.this.evaluationTableList);

                            if (tableList.size() < currentNum || evaluationTableList.size() >= countNum) {
                                evaluateDetailsTeacherContentRecycler.setNoMore(true);
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });
    }


    private void setBackgroundcolorById(int textId, int numId) {
        for (TextView textView : mTextViewList) {
            if (textView.getId() == textId || textView.getId() == numId) {
                textView.setTextColor(getResources().getColor(R.color.colorMain));
            } else {
                textView.setTextColor(getResources().getColor(R.color.color_item_text));
            }
        }
    }
}
